import {designPage, onBeforeUnmount} from "@peryl/react-compose";
import {createEffects} from "@peryl/utils/createEffects";

import {createBindingRunningState, PlainBindingNamespace, PlainRuleNamespace, RuleEditor} from "../../packages";
import _ruleData from './rule.data.json';
import _ruleOuterVariables from './ruleOuterVariables.data.json';
import _ruleInnerVariables from './ruleInnerVariables.data.json';
import {useBindingEditorOption, useRuleEditorOption} from "../module/cms-visual-editor";

const ruleMetas = _ruleData as PlainRuleNamespace.iRuleMeta[];
const outerVariables = _ruleOuterVariables as PlainBindingNamespace.iBindingVariables;
const innerVariables = _ruleInnerVariables as PlainBindingNamespace.iBindingVariables;

export default designPage(() => {

  const elStyles = { height: '100vh', width: '100vw' };

  /*这里模拟外部传递额外的绑定变量 bindingProvideData 给 rule editor*/
  const { effects: bindingRunningEffects } = createEffects();

  /*这里测试RuleEditor，创建一个外部的变量引擎状态，模拟规则运行时的外部上下文变量*/
  const bindingEditorOption = useBindingEditorOption({ isRunning: false });
  const bindingRunningState = createBindingRunningState({
    runningOption: bindingEditorOption,
    getOriginVariables: () => outerVariables,
    effects: bindingRunningEffects,
  });

  const ruleEditorOption = useRuleEditorOption({
    isRunning: false,
    data: {
      ruleMetas,
      ruleVariables: innerVariables,
      getBindingProvideData: () => bindingRunningState.bindingProvideData.value,
    }
  });
  /*先等外部的绑定变量初始化完毕再初始化 rule variables*/
  bindingRunningState.checkBindingVariables().then(() => {ruleEditorOption.editorRuleState.bindingRunningState.checkBindingVariables();});

  onBeforeUnmount(() => {bindingRunningEffects.clear();});
  return () => (
    <div style={elStyles}>
      {bindingRunningState.state.deferMetas && (
        <RuleEditor option={ruleEditorOption}/>
      )}
    </div>
  );
});
